import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class AnimatedAddGoodsPage extends StatefulWidget {
  const AnimatedAddGoodsPage({super.key});

  @override
  State<AnimatedAddGoodsPage> createState() => _AnimatedAddGoodsPagePageState();
}

class _AnimatedAddGoodsPagePageState extends State<AnimatedAddGoodsPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: HomePage(),
    );
  }
}

class Product {
  final String name;
  final String description;
  final double price;
  final String imageUrl;

  Product({
    required this.name,
    required this.description,
    required this.price,
    required this.imageUrl,
  });
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  // 创建10个商品数据
  final List<Product> products = List.generate(
    10,
    (index) => Product(
      name: '商品 ${index + 1}',
      description: '这是商品 ${index + 1} 的详细描述信息',
      price: 99.99 + index * 10,
      imageUrl: 'https://picsum.photos/seed/product$index/200/200',
    ),
  );

  final GlobalKey _cartKey = GlobalKey();
  Offset? _cartPosition;
  List<_FlyingItemController> _flyingItems = [];

  @override
  void initState() {
    super.initState();
    // 在下一帧获取购物车位置
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _getCartPosition();
    });
  }

  // 获取购物车位置
  void _getCartPosition() {
    final RenderBox? cartRenderBox = 
        _cartKey.currentContext?.findRenderObject() as RenderBox?;
    if (cartRenderBox != null) {
      final position = cartRenderBox.localToGlobal(
        Offset(cartRenderBox.size.width / 2 -35, cartRenderBox.size.height / 2 -105),
      );
      setState(() {
        _cartPosition = position;
      });
    }
  }

  // 添加飞行动画项目
  void _addFlyingItem(GlobalKey itemKey, String imageUrl) {
    if (_cartPosition == null) {
      _getCartPosition();
      // 延迟执行以确保购物车位置已获取
      Future.delayed(const Duration(milliseconds: 100), () {
        if (_cartPosition != null) {
          _startFlyingAnimation(itemKey, imageUrl);
        }
      });
      return;
    }

    _startFlyingAnimation(itemKey, imageUrl);
  }

  void _startFlyingAnimation(GlobalKey itemKey, String imageUrl) {
    final RenderBox? renderBox = 
        itemKey.currentContext?.findRenderObject() as RenderBox?;
    
    if (renderBox != null && _cartPosition != null) {
      final startPosition = renderBox.localToGlobal(
        Offset(renderBox.size.width / 2, renderBox.size.height / 2 - 80),
      );

      final flyingItemController = _FlyingItemController(
        startPosition: startPosition,
        endPosition: _cartPosition!,
        imageUrl: imageUrl,
        size: renderBox.size,
        vsync: this,
      );

      setState(() {
        _flyingItems.add(flyingItemController);
      });

      flyingItemController.controller.forward().whenComplete(() {
        if (mounted) {
          setState(() {
            _flyingItems.remove(flyingItemController);
          });
        }
        flyingItemController.controller.dispose();
      });
    }
  }

  @override
  void dispose() {
    for (var item in _flyingItems) {
      item.controller.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Animated')),
      body: Stack(
        children: [
          // 商品列表
          ListView.builder(
            itemCount: products.length,
            itemBuilder: (context, index) {
              return ProductItem(
                product: products[index],
                onAddToCart: (key) => _addFlyingItem(key, products[index].imageUrl),
              );
            },
          ),
          
          // 固定在右上角的购物车图标
          Positioned(
            key: _cartKey,
            right: 20,
            top: 20, // 相对于Scaffold的body，不需要额外加上通知栏和标题栏高度
            child: Container(
              width: 50,
              height: 50,
              decoration: BoxDecoration(
                color: Colors.blue,
                borderRadius: BorderRadius.circular(25),
              ),
              child: const Icon(
                Icons.shopping_cart,
                color: Colors.white,
              ),
            ),
          ),
          
          // 飞行中的动画元素
          ..._flyingItems.map((item) => item.widget).toList(),
        ],
      ),
    );
  }
}

class ProductItem extends StatelessWidget {
  final Product product;
  final Function(GlobalKey) onAddToCart;
  final GlobalKey _imageKey = GlobalKey();

  ProductItem({
    super.key,
    required this.product,
    required this.onAddToCart,
  });

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.all(10),
      child: Padding(
        padding: const EdgeInsets.all(10),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 商品图片
            Container(
              key: _imageKey,
              width: 80,
              height: 80,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                image: DecorationImage(
                  image: NetworkImage(product.imageUrl),
                  fit: BoxFit.cover,
                ),
              ),
            ),
            
            const SizedBox(width: 10),
            
            // 商品信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    product.name,
                    style: const TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 5),
                  Text(
                    product.description,
                    style: const TextStyle(
                      fontSize: 14,
                      color: Colors.grey,
                    ),
                  ),
                  const SizedBox(height: 10),
                  Text(
                    '¥${product.price.toStringAsFixed(2)}',
                    style: const TextStyle(
                      fontSize: 16,
                      color: Colors.red,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
            ),
            
            // 加入购物车按钮
            IconButton(
              icon: const Icon(Icons.add_shopping_cart),
              onPressed: () => onAddToCart(_imageKey),
            ),
          ],
        ),
      ),
    );
  }
}

class _FlyingItemController {
  final Offset startPosition;
  final Offset endPosition;
  final String imageUrl;
  final Size size;
  final AnimationController controller;
  late final Animation<Offset> positionAnimation;
  late final Animation<double> scaleAnimation;
  late final Animation<double> parabolicAnimation;
  late final Widget widget;

  _FlyingItemController({
    required this.startPosition,
    required this.endPosition,
    required this.imageUrl,
    required this.size,
    required TickerProvider vsync,
  }) : controller = AnimationController(
         duration: const Duration(milliseconds: 800),
         vsync: vsync,
       ) {
    positionAnimation = Tween<Offset>(
      begin: startPosition,
      end: endPosition,
    ).animate(CurvedAnimation(
      parent: controller,
      curve: Curves.linear, // 使用线性曲线，抛物线效果通过自定义动画实现
    ));
    
    // 缩放动画，从原始大小逐渐变小
    scaleAnimation = Tween<double>(
      begin: 1.0,
      end: 0.2,
    ).animate(CurvedAnimation(
      parent: controller,
      curve: Curves.easeInOut,
    ));
    
    // 抛物线动画（垂直方向的偏移）
    parabolicAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: controller,
      curve: Curves.easeIn, // 使用easeOut曲线实现抛物线效果
    ));
    
    widget = AnimatedBuilder(
      animation: controller,
      builder: (context, child) {
        // 计算抛物线偏移量
        // 创建一个抛物线轨迹: y = -a * x * (x - 1)，其中x是进度(0-1)，y是垂直偏移
        final progress = parabolicAnimation.value;
        final parabolicOffset = -100 * 4 * progress * (1 - progress); // 抛物线公式，最大偏移100
        
        // 计算当前位置
        final currentX = positionAnimation.value.dx;
        final currentY = positionAnimation.value.dy + parabolicOffset;
        
        return Positioned(
          left: currentX - (size.width / 2) * scaleAnimation.value,
          top: currentY - (size.height / 2) * scaleAnimation.value,
          child: Transform.scale(
            scale: scaleAnimation.value,
            child: Container(
              width: size.width,
              height: size.height,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                image: DecorationImage(
                  image: NetworkImage(imageUrl),
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}